from django.shortcuts import render
from order.models import OrderInfo
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from alipay import Alipay
from .models import Payment
from django.conf import settings

# 1. 记录 APPID 和 网关(类似于 api.meiduo.site)
# 2. 我们需要创建2套 公钥 和 秘钥
#   2.1 我们的工程一套 (公钥和私钥)
#   2.2 支付宝一套 (公钥和私钥)

class PaymentView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self,request,order_id):
        # 1.需要前端把订单ID传递过来
        # 2.根据id查询信息
        try: # 保证查询准确度，查询订单应当是未支付状态的订单
            order = OrderInfo.objects.get(
                order_id=order_id,
                user=request.user,
                status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 3.创建alipay
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  )

        # 4.生成order_string
        subject = "测试订单"
        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=subject,
            return_url="http://www.meiduo.site:8080/pay_success.html",
            notify_url=None)  # 可选, 不填则使用默认notify url)

        # 5.拼接最终的url
        alipay_url = settings.ALIPAY_URL + '?' + order_string
        return Response({'alipay_url':alipay_url})


class PaymentStatuView(APIView):
    def put(self,request):
        # 1. 根据回调的url 来获取参数,并对参数进行处理
        signature = request.query_params.dict().pop('sign')

        # 2. 创建alipay的对象
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG)

        # 3. 查询交易状态
        success = alipay.verify(data,signature)
        if success:
            # 4. 如果成功,则将订单信息和支付宝订单 保存,并且改变订单信息
            trade_no = data.get('trade_no')
            out_trade_no = data.get('out_trade_no')
            Payment.objects.create(
                order_id=out_trade_no,
                trade_id=trade_no  )
            OrderInfo.objects.filter(order_id=out_trade_no).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            return Response({"trade_id": out_trade_no})

        else:
            # 5. 如果失败,返回400
            return Response(status=status.HTTP_400_BAD_REQUEST)